/**
 * 小程序上传API调用示例
 * 展示在实际项目中如何使用上传服务
 */

const axios = require('axios');

// 配置上传服务地址
const UPLOAD_SERVICE_URL = 'http://localhost:3000';
const API_SECRET_KEY = 'yueqiankejiyueqiankejiyueqiankeji';

/**
 * 小程序配置管理类
 */
class MiniProgramUploader {
    constructor(serviceUrl = UPLOAD_SERVICE_URL) {
        this.serviceUrl = serviceUrl;
    }

    /**
     * 上传小程序代码
     * @param {Object} config 上传配置
     * @param {string} config.appid 小程序AppID
     * @param {string} config.privateKey 私钥内容
     * @param {string} config.backendDomain 后端域名
     * @param {number} config.uniacid uniacid
     * @param {string} config.entryPagePath 首页路径
     */
    async uploadCode(config) {
        try {
            console.log(`🚀 开始上传小程序: ${config.appid}`);
            
            const response = await axios.post(`${this.serviceUrl}/upload`, config, {
                timeout: 300000, // 5分钟超时
                headers: {
                    'Content-Type': 'application/json',
                    'X-API-Key': API_SECRET_KEY
                }
            });

            if (response.data.success) {
                console.log('✅ 上传成功:', response.data.data);
                return response.data.data;
            } else {
                throw new Error(response.data.message);
            }
        } catch (error) {
            if (error.response) {
                console.error('❌ 上传失败:', error.response.data);
                throw new Error(error.response.data.message || '上传失败');
            } else {
                console.error('❌ 网络错误:', error.message);
                throw error;
            }
        }
    }

    /**
     * 检查服务是否可用
     */
    async checkHealth() {
        try {
            const response = await axios.get(`${this.serviceUrl}/health`);
            return response.data.success;
        } catch (error) {
            console.error('服务健康检查失败:', error.message);
            return false;
        }
    }
}

/**
 * 示例1: 单个小程序上传
 */
async function example1_singleUpload() {
    console.log('\n=== 示例1: 单个小程序上传 ===');
    
    const uploader = new MiniProgramUploader();
    
    // 检查服务是否可用
    const isHealthy = await uploader.checkHealth();
    if (!isHealthy) {
        console.error('❌ 上传服务不可用');
        return;
    }

    const config = {
        appid: 'wx1234567890abcdef',
        privateKey: `-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...
-----END PRIVATE KEY-----`,
        backendDomain: 'api.example.com',
        uniacid: 123,
        entryPagePath: 'pages/index/index'
    };

    try {
        const result = await uploader.uploadCode(config);
        console.log('上传结果:', result);
    } catch (error) {
        console.error('上传失败:', error.message);
    }
}

/**
 * 示例2: 批量上传多个小程序
 */
async function example2_batchUpload() {
    console.log('\n=== 示例2: 批量上传多个小程序 ===');
    
    const uploader = new MiniProgramUploader();
    
    // 多个小程序配置
    const configs = [
        {
            appid: 'wx1111111111111111',
            privateKey: 'PRIVATE_KEY_1',
            backendDomain: 'api1.example.com',
            uniacid: 101,
            entryPagePath: 'pages/index/index'
        },
        {
            appid: 'wx2222222222222222',
            privateKey: 'PRIVATE_KEY_2',
            backendDomain: 'api2.example.com',
            uniacid: 102,
            entryPagePath: 'pages/home/home'
        }
    ];

    for (const config of configs) {
        try {
            console.log(`\n上传小程序: ${config.appid}`);
            const result = await uploader.uploadCode(config);
            console.log('✅ 成功:', result);
            
            // 等待一段时间再上传下一个，避免频繁请求
            await new Promise(resolve => setTimeout(resolve, 2000));
        } catch (error) {
            console.error(`❌ 失败 ${config.appid}:`, error.message);
        }
    }
}

/**
 * 示例3: 从配置文件读取参数上传
 */
async function example3_configFile() {
    console.log('\n=== 示例3: 从配置文件读取参数 ===');
    
    const fs = require('fs');
    const path = require('path');
    
    // 模拟配置文件内容
    const configData = {
        miniPrograms: [
            {
                name: '测试小程序1',
                appid: 'wx1111111111111111',
                privateKeyFile: './keys/private.wx1111111111111111.key',
                backendDomain: 'api.test1.com',
                uniacid: 201,
                entryPagePath: 'pages/index/index'
            },
            {
                name: '测试小程序2',
                appid: 'wx2222222222222222',
                privateKeyFile: './keys/private.wx2222222222222222.key',
                backendDomain: 'api.test2.com',
                uniacid: 202,
                entryPagePath: 'pages/main/main'
            }
        ]
    };

    const uploader = new MiniProgramUploader();

    for (const mpConfig of configData.miniPrograms) {
        try {
            console.log(`\n处理小程序: ${mpConfig.name} (${mpConfig.appid})`);
            
            // 读取私钥文件（这里模拟）
            // const privateKey = fs.readFileSync(mpConfig.privateKeyFile, 'utf8');
            const privateKey = 'MOCK_PRIVATE_KEY'; // 实际使用时替换为真实读取
            
            const uploadConfig = {
                appid: mpConfig.appid,
                privateKey: privateKey,
                backendDomain: mpConfig.backendDomain,
                uniacid: mpConfig.uniacid,
                entryPagePath: mpConfig.entryPagePath
            };

            const result = await uploader.uploadCode(uploadConfig);
            console.log('✅ 上传成功:', result);
            
        } catch (error) {
            console.error(`❌ ${mpConfig.name} 上传失败:`, error.message);
        }
    }
}

/**
 * 示例4: 环境变量配置
 */
async function example4_envConfig() {
    console.log('\n=== 示例4: 使用环境变量配置 ===');
    
    // 从环境变量读取配置
    const config = {
        appid: process.env.MP_APPID || 'wx1234567890abcdef',
        privateKey: process.env.MP_PRIVATE_KEY || 'MOCK_PRIVATE_KEY',
        backendDomain: process.env.BACKEND_DOMAIN || 'api.example.com',
        uniacid: parseInt(process.env.UNIACID) || 123,
        entryPagePath: process.env.ENTRY_PAGE_PATH || 'pages/index/index'
    };

    console.log('配置信息:', {
        ...config,
        privateKey: '***隐藏***'
    });

    const uploader = new MiniProgramUploader();
    
    try {
        const result = await uploader.uploadCode(config);
        console.log('✅ 上传成功:', result);
    } catch (error) {
        console.error('❌ 上传失败:', error.message);
    }
}

/**
 * 主函数
 */
async function main() {
    console.log('🎯 微信小程序上传API调用示例');
    console.log('请确保上传服务已启动: npm start');
    
    try {
        // 运行示例（根据需要启用）
        // await example1_singleUpload();
        // await example2_batchUpload();
        // await example3_configFile();
        await example4_envConfig();
        
    } catch (error) {
        console.error('示例运行失败:', error);
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    main();
}

module.exports = {
    MiniProgramUploader,
    example1_singleUpload,
    example2_batchUpload,
    example3_configFile,
    example4_envConfig
}; 